package view.swing.tiles;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import model.iview.ITile;
import view.swing.tiles.TileDragDroppable.AllowedState;

public class Placeur implements MouseListener {

    /**
     * 
     */
    private static final long serialVersionUID = -743255426687237920L;
    private static TileDragDroppable currentTile = null;

    public static void drop(TileDragDroppable source, TileDragDroppable dest) {
        if (source == dest) {
            return;
        }

        if (source == null || dest == null || !source.hasTileHere()) {
            return;
        }

        if (dest.hasTileHere()) { // Il faut inverser les deux
            ITile tmp = dest.drag();
            dest.drop(source.drag());
            
            source.drop(tmp);
        } else {
            dest.drop(source.drag());
            dest.setSource(source.getSource() != null ? source.getSource()
                    : source);
        }

        source.setSelected(false);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        if (!(e.getSource() instanceof TileDragDroppable)) {
            return;
        }

        TileDragDroppable tileDD = ((TileDragDroppable) e.getSource());

        if (tileDD.getAllowedState() == AllowedState.NONE) {
            return;
        }

        if ((e.getButton() != MouseEvent.BUTTON1 || e.getClickCount() > 1)
                && tileDD.getSource() != null && tileDD.hasTileHere()) {
            TileDragDroppable destination = tileDD;
            while (destination != null && destination.hasTileHere()) {
                destination = destination.getSource();
            }
            if (destination == null) return;
            if (tileDD.getTile().isOldJoker()) {
                tileDD.getTile().clearJokerValue();
            }
            destination.drop(tileDD.drag());
            tileDD.setSource(null);
            return;
        }
    }

    public static void reset() {
        if (currentTile != null) {
            currentTile.setSelected(false);
            currentTile = null;
        }

    }

    @Override
    public void mouseEntered(MouseEvent arg0) {

    }

    @Override
    public void mouseExited(MouseEvent arg0) {

    }

    @Override
    public void mousePressed(MouseEvent arg0) {

    }

    @Override
    public void mouseReleased(MouseEvent arg0) {

    }

}